package org.ehe.business.supplier.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.ehe.business.supplier.domain.SupplierCategory;
import org.ehe.business.supplier.domain.vo.SupplierCategoryVO;
import org.ehe.business.supplier.mapper.SupplierCategoryMapper;
import org.ehe.business.supplier.service.SupplierCategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author :zhangnn
 * @className :SupplierCategoryServiceImpl
 * @description: TODO
 * @date 2025-07-23 11:00:28
 */
@Service
public class SupplierCategoryServiceImpl extends ServiceImpl<SupplierCategoryMapper, SupplierCategory> implements SupplierCategoryService {
    /**
     * 获取供应商分类列表
     * @param categoryIds
     * @return
     */
    @Override
    public List<SupplierCategoryVO> getCategoriesByIds(List<Long> categoryIds) {
        List<SupplierCategory> allCategories = new ArrayList<>();
        if(categoryIds.isEmpty()){
            allCategories = baseMapper.selectList(new QueryWrapper<>());
        } else {
            // 1. 先查询所有符合条件的分类（根据ID列表过滤）
            allCategories = baseMapper.selectByIds(categoryIds);
        }
        if (allCategories.isEmpty()) {
            return Collections.emptyList();
        }
        List<SupplierCategoryVO> categoryVOS = new ArrayList<>();
        for (SupplierCategory allCategory : allCategories) {
            SupplierCategoryVO vo = new SupplierCategoryVO();
            BeanUtils.copyProperties(allCategory,vo);
            categoryVOS.add(vo);
        }

        // 2. 递归构建树形结构
        return categoryVOS;
        //return buildCategoryTree(categoryVOS, 0L); // 假设顶级分类的parentId为0
    }

    /**
     * 递归构建分类树形结构
     * @param allCategories 所有分类列表
     * @param parentId 父级ID（初始为顶级父ID，如0）
     * @return 树形结构的分类列表
     */
    private List<SupplierCategoryVO> buildCategoryTree(List<SupplierCategoryVO> allCategories, Long parentId) {
        List<SupplierCategoryVO> childCategories = new ArrayList<>();

        for (SupplierCategoryVO category : allCategories) {
            // 找到当前父ID下的子分类
            if (Objects.equals(category.getParentId(), parentId)) {
                // 递归查询当前分类的子分类
                List<SupplierCategoryVO> children = buildCategoryTree(allCategories, category.getId());
                category.setChildCategory(children);
                childCategories.add(category);
            }
        }

        return childCategories;
    }
}
